﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace Logo
{
    public partial class LogoDraw : UserControl
    {
        private PointF currentPosition;
        public PointF CurrentPosition
        {
            get { return currentPosition; }
            set { currentPosition = value; }
        }

        private double angle;
        public double Angle
        {
            get { return angle; }
            set { angle = value; }
        }

        private bool penActive;
        public bool PenActive
        {
            get { return penActive; }
            set { penActive = value; }
        }

        private Pen pen;
        public Pen Pen
        {
            get { return pen; }
            set { pen = value; }
        }

        private Graphics g;
        public Graphics Graphics
        {
            get { return g; }
            set { g = value; }
        }

        public LogoDraw()
        {
            InitializeComponent();
            this.currentPosition.X = 150;
            this.currentPosition.Y = 150;
            pen = new Pen(new SolidBrush(Color.Red), 2);
        }

        public void Forward(int distance)
        {
            PointF p1 = currentPosition;
            PointF p2 = new PointF((float)(p1.X + Math.Cos(angle / 180 * Math.PI) * distance), p1.Y + (float)(Math.Sin(angle / 180 * Math.PI) * distance));

            if (penActive)
            {
                g.DrawLine(pen, p1, p2);
            }

            currentPosition = p2;
        }

        public void Rotate(double angle)
        {
            this.angle += angle;
        }

        private void buttonRun_Click(object sender, EventArgs e)
        {
            // Refresh picture box
            pictureBox.Refresh();

            // Clear log
            textBoxLog.Clear();

            // Init pen
            penActive = true;

            // Init image
            if (pictureBox.Image != null)
            {
                pictureBox.Image.Dispose();
            }
            pictureBox.Image = new Bitmap(3000, 3000);

            // Init graphics
            g = Graphics.FromImage(pictureBox.Image);

            currentPosition = new Point(0, 0);

            angle = 0;

            // Run Invoker
            Invoker.functions = new Dictionary<string, FunctionMaker>();
            Invoker invoker = new Invoker(this, textBox.Text, null);

            try
            {
                invoker.Run();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }

        public void AddLog(string log)
        {
            //textBoxLog.AppendText(log + "\n");
        }
    }
}